<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace app\category\model;//Demo插件英文名，改成你的插件英文就行了
use think\Model;
use tree\Tree;
use think\Db;
class Category extends Model
{

    protected $type = [
        'more' => 'array',
    ];
    protected $table='dp_category_category';

    /**
     * 获取多条数据
     * @param string $table  传去掉表前缀的表名
     * @param array  $where  查询条件
     * @param string $field  查询的字段
     * @param string $order  排序
     * @param int    $page_number 页数
     * @param int    $page_size  页面大小
     */
    public function getListByWhere($table,$where,$field,$order = 'id',$page_number=1,$page_size=10){
        $result = Db::name($table)
            ->field($field)
            ->where($where)
            ->order($order)
            ->page($page_number,$page_size)
            ->select();
        return $result;
    }


    /**
     * 获取总条数
     * @param string $table  传去掉表前缀的表名
     * @param array  $where  查询条件
     */
    public function getByWhereCount($table,$where){
        $result = Db::name($table)
            ->where($where)
            ->count();
        //输出最后一个sql语句
        //echo  DB::name($table)->getLastSql();
        return $result;
    }


    /**
     * 生成分类 select树形结构
     * @param int $selectId 需要选中的分类 id
     * @param int $currentCid 需要隐藏的分类 id
     * @return string
     */
    public function adminCategoryTree($selectId = 0, $currentCid = 0)
    {
        $where = ['isdel' => 2];
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }
        $categories = $this->order("paixu ASC")->where($where)->select();
        $categories=collection($categories)->toArray();
        $options=array(0=>'顶级分类');
        foreach ($categories as $item) {
           $options[$item['id']]=$item['name'];
        }

        return $options;
    }

    /**
     * 格式化输出添加分页数据
     * @param mixed $data 数据信息
     * @param string $msg 提示信息
     * @param int $page 当前页数
     * @param int $count 总页数
     * @param int $code  状态码
     */
    public  function outFormats($data, $msg,$codeData, $page = 1, $count = 0, $code = 0) {
        header('Content-type: application/json;charset=utf-8');
        $ajax = array(
            // 'data' => array('code'=>1,'data'=>$data),
            'data' => $data,
            'msg' => $msg,
            'codeData'=>$codeData,
            'page' => $page,
            'count' => $count,
            'code' => $code
        );

        echo json_encode($ajax,JSON_UNESCAPED_UNICODE);die;
    }

    /**
     * @param int|array $currentIds 获取树形分类
     * @param string $tpl 模板
     * @return string
     */
    public function adminCategoryTableTree($currentIds = 0, $tpl = '')
    {

        $where = ['isdel' => 2];
//        if (!empty($currentCid)) {
//            $where['id'] = ['neq', $currentCid];
//        }

        $categories = $this->order("paixu ASC")->where($where)->select();
        $categories=collection($categories)->toArray();
        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }
        $newCategories = [];
        foreach ($categories as $item) {
            $item['checked'] = in_array($item['id'], $currentIds) ? "checked" : "";
            $item['url']     = url('index', ['id' => $item['id']]);
            $item['icon']=get_thumb($item['icon']);
            $item['status'] = $item['status']=='1'?'启用':'禁用';
            $item['str_action'] = '<a href="' .url('add', ["parent" => $item['id']]) . '">添加子分类</a> | <a href="' . url('edit', ["id" => $item['id']]) . '">修改</a> | <a class="js-ajax-delete" href="' . url('categoryDelete', ["id" => $item['id']]) . '">删除</a> ';
            array_push($newCategories, $item);
        }
        $tree->init($newCategories);
        if (empty($tpl)) {
            $tpl = "<tr>
                        <td><input name='' type='text' size='3' value='\$id' class='input-order'></td>
                        <td>\$spacer <a href='' target='_blank'>\$name</a></td>
                        <td><img src='\$icon' height='40'></td>
                        <td>\$status</td>
                        <td>\$type</td>
                        <td>\$paixu</td>
                        <td>\$createtime</td>
                        <td>\$str_action</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);
        return $treeStr;
    }

    /**
     * 添加分类
     * @param $data
     * @return bool
     */
    public function addCategory($data)
    {
        $result=$this->allowField(true)->data($data, true)->isUpdate(false)->save();
        return $result;
    }

    public function editCategory($data)
    {
        $result = true;

        $id          = intval($data['id']);
        $parentId    = intval($data['parent_id']);
        $oldCategory = $this->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath-$id";
            }
        }

        if (empty($oldCategory) || empty($newPath)) {
            $result = false;
        } else {


            $data['path'] = $newPath;
            if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }
            $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

            $children = $this->field('id,path')->where('path', 'like', "%-$id-%")->select();

            if (!empty($children)) {
                foreach ($children as $child) {
                    $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
                    $this->isUpdate(true)->save(['path' => $childPath], ['id' => $child['id']]);
                }
            }

            $routeModel = new RouteModel();
            if (!empty($data['alias'])) {
                $routeModel->setRoute($data['alias'], 'portal/List/index', ['id' => $data['id']], 2, 5000);
                $routeModel->setRoute($data['alias'] . '/:id', 'portal/Article/index', ['cid' => $data['id']], 2, 4999);
            } else {
                $routeModel->deleteRoute('portal/List/index', ['id' => $data['id']]);
                $routeModel->deleteRoute('portal/Article/index', ['cid' => $data['id']]);
            }

            $routeModel->getRoutes(true);
        }
        return $result;
    }

    /**
     * 更新数据
     * @param string $table
     * @param array  $where 条件
     * @param array  $data  更新的数据
     */
    public function saveData($table,$where,$data){
        $result = Db::name($table)
            ->where($where)
            ->update($data);
        //输出最后一个sql语句
        //echo  DB::name($table)->getLastSql();
        return $result;
    }


}